package cn.wolfcode.interceptor;

import cn.wolfcode.domain.Result;
import cn.wolfcode.util.JWTUtils;
import com.alibaba.fastjson.JSON;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

@Component

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {

        String token = request.getHeader("token");

        try { //解析令牌
            JWTUtils.parseToken(token);
            //放行
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            //拦截反馈内容
            Result notLogin = Result.error("NOT_LOGIN");
            response.setContentType("application/json;charset=utf-8");
            //将对象在转换为json
            String jsonString = JSON.toJSONString(notLogin);

            response.getWriter().write(jsonString);
            return false;

        }
    }


}
